package com.fxd.rocketmq.config;

import com.fxd.rocketmq.core.RocketMqEvent;
import com.fxd.rocketmq.enums.RocketMqConfigEnums;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author xudongfu
 * @date 2023/02/22
 */
@Slf4j
@Configuration
public class RocketMqConsumerConfig {

    @Value("${rocketmq.namesrvAddr}")
    private String namesrvAddr;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Bean
    public MessageListenerOrderly messageListenerOrderly() {
        return new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                try {
                    context.setAutoCommit(true);
                    if (msgs.size() == 0) {
                        return ConsumeOrderlyStatus.SUCCESS;
                    }

                    for (MessageExt msg : msgs) {
                        // 使用spring做事件转发
                        publisher.publishEvent(new RocketMqEvent(msg));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT;
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        };
    }

    @Bean
    public DefaultMQPushConsumer defaultConsumer(MessageListenerOrderly messageListenerOrderly) {
        log.info("defaultConsumer 正在创建---------------------------------------");
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(RocketMqConfigEnums.TEST.getGroup());
        consumer.setNamesrvAddr(namesrvAddr);
        consumer.setConsumeThreadMin(1);
        consumer.setConsumeThreadMax(1);
        consumer.setConsumeMessageBatchMaxSize(1);
        // 设置监听
        consumer.registerMessageListener(messageListenerOrderly);

        /**
         * 设置consumer第一次启动是从队列头部开始还是队列尾部开始
         * 如果不是第一次启动，那么按照上次消费的位置继续消费
         */
        consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
        /**
         * 设置消费模型，集群还是广播，默认为集群
         */
        consumer.setMessageModel(MessageModel.CLUSTERING);

        try {
            // 设置该消费者订阅的主题和tag，如果订阅该主题下的所有tag，则使用*,

            consumer.subscribe(RocketMqConfigEnums.TEST.getTopic(),
                    RocketMqConfigEnums.TEST.getTag());
            consumer.start();
            log.info("consumer 创建成功");
        } catch (MQClientException e) {
            log.error("consumer 创建失败!");
        }
        return consumer;
    }

}
